package com.sinsz.nacos.listener;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池工程定义
 * @author chenjianbo
 * @date 2018-3-2
 */
public class NacosThreadFactory implements ThreadFactory {

    /**
     * 线程池编号
     */
    private static AtomicInteger pool = new AtomicInteger(1);
    /**
     * 线程编号
     */
    private static AtomicInteger thread = new AtomicInteger(1);

    private final ThreadGroup group;

    private String threadName;

    private boolean isDaemon;

    public NacosThreadFactory() {
        this("pool");
    }

    NacosThreadFactory(String threadName) {
        this(threadName, false);
    }

    private NacosThreadFactory(String threadName, boolean isDaemon) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.threadName = threadName + "-" + String.format("%03d", pool.getAndIncrement()) + "-thread-";
        this.isDaemon = isDaemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,threadName + String.format("%03d", thread.getAndIncrement()),0);
        t.setDaemon(isDaemon);
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
